<template>
  <div class="container">
    <div class="segmented__group" ref="segmented__group">
      <div class="segmented__item_select" ref="segmented__item_select"></div>
      <div
        :class="['segmented__item', isSelect == index ? 'is-select' : '']"
        v-for="(item, index) in group"
        :key="index"
        ref="segmented__item"
        @click="
          e => {
            clickTab(e, index)
          }
        "
      >
        {{ item }}
      </div>
    </div>
  </div>
</template>

<script setup>
  import { ref, onMounted } from 'vue'
  const group = [
    'Delicacy',
    'Desserts&Drinks',
    'Fresh foods',
    'Supermarket',
    'Fresh foods',
    'Supermarket',
  ]
  const segmented__group = ref(null)
  const segmented__item = ref(null)
  const isSelect = ref(0)
  const clickTab = (e, index) => {
    isSelect.value = index
    const translateX = e.target.offsetLeft
    const selectWidth =
      segmented__item.value[isSelect.value].getBoundingClientRect().width
    segmented__item_select.value.style.width = `${selectWidth}px`
    segmented__item_select.value.style.transform = `translateX(${translateX}px)`


    // const lineTabs_offsetWidth = segmented__group.value.offsetWidth
    // const dom = e.target
    // const domoffsetWidth = dom.offsetLeft
    // const diffWidth = (lineTabs_offsetWidth - dom.offsetWidth) / 2
    // const targetOffset = domoffsetWidth - diffWidth

    // // 未超出中间值
    // segmented__group.value.scrollLeft = targetOffset < 0 ? 0 : targetOffset
  }
  const segmented__item_select = ref(null)
  onMounted(() => {
    const selectWidth =
      segmented__item.value[isSelect.value].getBoundingClientRect().width
    const translateX = segmented__item.value[isSelect.value].offsetLeft
    segmented__item_select.value.style.width = `${selectWidth}px`
    segmented__item_select.value.style.transform = `translateX(${translateX}px)`
    segmented__item_select.value.style.display = 'block'
  })
</script>

<style lang="scss" scoped>
  .container {
    height: 100%;
    margin: 20px auto auto;
    .segmented__group {
      display: inline-flex;
      align-items: center;
      position: relative;
    //   overflow-x: auto;
      .segmented__item {
        display: flex;
        align-items: center;
        cursor: pointer;
        border-radius: 36px;
        padding: 0 11px;
        height: 32px;
        line-height: 32px;
        transition: all 0.3s;
        white-space: nowrap;
        &:not(.is-select):hover {
          background: gray;
        }
      }
      .is-select {
        color: #fff;
      }
      .segmented__item_select {
        position: absolute;
        top: 0;
        left: 0;
        height: 100%;
        background: #f00;
        transition: all 0.3s;
        border-radius: 36px;
        z-index: -1;
      }
    }
  }
</style>
